﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SpyApp.Models;
using SpyApp.Models;
using SpyApp.Models.EntytiRepossitory;
using SpyApp.Models.BaseCommon;
using SpyApp.Models.BaseCommon.Enum;
using System.Globalization;
using System.Collections.Specialized;
using System.Text.RegularExpressions;


namespace SpyApp.Controllers
{
    public class MobileController : ApiController
    {
        private UserRepository userRepository;

        public MobileController()
        {
            this.userRepository = new UserRepository();
        }

        //api/users
        [HttpGet]
        [ActionName("GetAllUser")]        
        public HttpResponseMessage GetAllUser()
        {
            /*Tam đóng phần kiểm tra quyền đăng nhập
             
            if (string.IsNullOrEmpty(userId))
                return Request.CreateErrorResponse(HttpStatusCode.NoContent, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_USERNAME);
            User _user = this.userRepository.GetUserById(userId);
            if (_user != null)
                if (_user.userType == Models.Enum.DBEntity.UserType.User)
                    return Request.CreateErrorResponse(HttpStatusCode.NoContent, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.USER_UNVALID_PERMISSION);
            */
           
            IEnumerable<User> user = this.userRepository.GetAllUser();
            if (user != null)
            {
                return Request.CreateResponse<IEnumerable<User>>(HttpStatusCode.OK, user);
            }
            else
                return Request.CreateResponse(HttpStatusCode.NotFound);                  
   
        }
        //api/user/5
        [HttpGet]
        [ActionName("GetUserById")]        
        public HttpResponseMessage GetUserById(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Request.CreateErrorResponse(HttpStatusCode.NoContent, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_USERNAME);
            AccountModel.WebServiceResult wsr = new AccountModel.WebServiceResult();
            try
            {
                User _user = this.userRepository.GetUserById(id);
                if (_user != null)
                {
                    if (_user.UserStatus == DBEntity.UserStatus.Waitting)
                        return Request.CreateErrorResponse(HttpStatusCode.NoContent, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.USER_NOT_ACTIVATED);
                    if (_user.UserStatus == DBEntity.UserStatus.Deactivated)
                        return Request.CreateErrorResponse(HttpStatusCode.NoContent, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.USER_IS_DEACTIVATED);

                    wsr.Status = HttpStatusCode.OK.ToString();
                    wsr.Id = _user.Id;
                    wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.LOGIN_SUCCESSFUL;
                    return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.Accepted, wsr);
                }
                else
                {
                    wsr.Status = HttpStatusCode.NotFound.ToString();
                    wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.USER_NOTFOUND;
                    return Request.CreateResponse(HttpStatusCode.NotFound,wsr);
                }
            }
            catch (Exception ex)
            {
                throw ExeptionUtils.ThrowCustomException(ex);
            }
        
        }

        [HttpPost]
        public HttpResponseMessage Login([FromBody] AccountModel.WebServiceRequest login)
        {
            
            if (string.IsNullOrEmpty(login.PassWord))
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_PASSWORD);
            if (string.IsNullOrEmpty(login.UserName))
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_EMAIL);
            
            AccountModel.WebServiceResult wsr = new AccountModel.WebServiceResult();
            try
            {
                
                User user = this.userRepository.Login(login.UserName, login.PassWord);
                if (user != null)
                {
                    wsr.Status = HttpStatusCode.Accepted.ToString();
                    wsr.Id = user.Id;
                    wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.LOGIN_SUCCESSFUL;
                    
                    string _deviceId = UpdateAndAddNewDevice(user.Id, login.Imei, login.Sn, login.DeviceName, login.OsVersion, login.OsBrand, login.ScreenSize, login.AppVersion, login.AppInstalledOn);
                    if (_deviceId == "0" || _deviceId == "3")
                        return Request.CreateResponse(HttpStatusCode.ExpectationFailed);
                    wsr.DeviceId = _deviceId.ToString();
                    // lưu History 
                    History _his = new History();
                    _his.UserId = user.Id;
                    _his.DateTimeLogin = DateTime.UtcNow;                    
                    _his.DeviceId = _deviceId.ToString();
                    this.userRepository.AddNewHistory(_his);
                    return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.Accepted, wsr);
                }
                else
                {
                    wsr.Status = HttpStatusCode.NotFound.ToString();
                    wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.USER_NOTFOUND;
                    return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.NotFound,wsr);
                }
            }
            catch (Exception ex)
            {                
                wsr.Status = HttpStatusCode.ExpectationFailed.ToString();                
                wsr.Message = ex.Message.ToString();
                return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.ExpectationFailed, wsr);
            }
        }

        [HttpPost]
        public HttpResponseMessage Confirm(string VerifyCode)
        {
            string _verifyCode = VerifyCode.Replace(" ","+");
           
            if (string.IsNullOrEmpty(VerifyCode))
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_ACTIVATION_CODE);
            try
            {
                User user = this.userRepository.VerifyUser(_verifyCode);
                if (user != null)
                {
                    user.UserStatus = DBEntity.UserStatus.Active;
                    this.userRepository.Update(user.Id, user);
                    return Request.CreateResponse<User>(HttpStatusCode.OK, user);
                }
                else
                    return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            catch (Exception ex)
            {
                throw ExeptionUtils.ThrowCustomException(ex);
            }
        }

        [HttpPost]
        public HttpResponseMessage AddNewUser([FromBody] AccountModel.WebServiceRegister newUser)            
        {
            AccountModel.WebServiceResult wsr = new AccountModel.WebServiceResult();
            if (string.IsNullOrEmpty(newUser.PassWord))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_PASSWORD);          
            if (string.IsNullOrEmpty(newUser.UserName))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_EMAIL);
            else
            {
                if (!IsValidEmail(newUser.UserName))
                {
                    wsr.Status = HttpStatusCode.BadRequest.ToString();
                    // wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.DUPLICATE_USERNAME;
                    wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.INVALID_EMAIL;
                    return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
                }
                //else
                //{
                //    if (!VerifyEmail(newUser.UserName))
                //    {
                //        wsr.Status = HttpStatusCode.BadRequest.ToString();
                //        // wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.DUPLICATE_USERNAME;
                //        wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMAIL_NOT_EXISTED;
                //        return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
                //    }
                //}
            }            
            if (this.ModelState.IsValid)
            {              
                try
                {

                    var _role = this.userRepository.GetRoleById("3");
                    //Device dv = new Device();
                    //dv.Id = Guid.NewGuid().ToString();
                    //dv.Sn = newUser.Sn;
                    //if (string.IsNullOrEmpty(newUser.DeviceName))
                    //    newUser.DeviceName = "Untitled Name";
                    //dv.DeviceName = newUser.DeviceName;
                    //dv.Imei1 = newUser.Imei;
                    //dv.OsVersion = newUser.OsVersion;
                    //dv.OsBrand = newUser.OsBrand;
                    //dv.ScreenSize = newUser.ScreenSize;
                    //dv.AppVersion = newUser.AppVersion;
                    //dv.AppInstalledOn = newUser.AppInstalledOn;
                    //dv.ExpireDate = DateTime.ParseExact(newUser.AppInstalledOn, "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture).AddDays(7);

                    User user = new User();
                    user.SnDeviceRegisted = new List<Device>();
                    //user.SnDeviceRegisted.Add(dv);
                    user.UserName = newUser.UserName;
                    user.UserInRoles = new List<Roles>();
                    user.UserInRoles.Add(_role);
                    user.PassWord = newUser.PassWord;
                    user.UserType = DBEntity.UserType.User;
                    user.Status = DBEntity.ObjectStatus.Active;
                    user.UserStatus = DBEntity.UserStatus.Waitting;
                    user.LastModifined = DateTime.UtcNow;

                    if (user != null)
                    {
                        try
                        {
                            User _newUser = this.userRepository.RegisterNewUser(user);

                            if (_newUser != null)
                            {
                                wsr.Status = HttpStatusCode.Created.ToString();
                                wsr.Id = _newUser.Id;
                                wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.USER_IS_CREATED;
                                var httpRespone = Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.Created, wsr);
                                string uri = Url.Link("DefaultApi", new { id = wsr.Id });
                                httpRespone.Headers.Location = new Uri(uri);
                                return httpRespone;
                            }
                            return Request.CreateResponse(HttpStatusCode.BadRequest);
                        }
                        catch (Exception ex)
                        {
                            wsr.Status = HttpStatusCode.BadRequest.ToString();
                            // wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.DUPLICATE_USERNAME;
                            wsr.Message = ex.Message.ToString();
                            return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
                        }
                    }
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }
                catch (Exception ex)
                {
                    throw ExeptionUtils.ThrowCustomException(ex);
                }
            }
            else
            {                
                return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
            }
        }
        
        public static bool IsValidEmail(string email)
        {
            Regex rx = new Regex(
            @"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
            return rx.IsMatch(email);
        }

        public bool VerifyEmail(string emailVerify)
        {
            using (WebClient webclient = new WebClient())
            {
                string url = "http://verify-email.org/"; 
                NameValueCollection formData = new NameValueCollection(); 
                formData["check"] = emailVerify;
                byte[] responseBytes = webclient.UploadValues(url, "POST", formData); 
                string response = System.Text.Encoding.ASCII.GetString(responseBytes); 
                if (response.Contains("Result: Ok"))
                {
                    return true;
                }
                    return false; 
            }
 
        }

        [HttpPut]
        public HttpResponseMessage UpdateUser(string id, string userName, string passWord, int age)
        {
            try
            {
                if ((this.ModelState.IsValid) && (id != null))
                {
                    User user = this.userRepository.GetUserById(id);
                    if (user != null)
                    {
                        user.UserName = userName;
                        user.PassWord = passWord;
                        user.Age = age;
                        user.LastModifined = DateTime.UtcNow;
                    }
                    else
                        return Request.CreateResponse(HttpStatusCode.NotFound);

                    if (userName != null)
                        user.UserName = userName;

                    bool result = this.userRepository.Update(user.Id, user);

                    if (result)
                        return Request.CreateResponse<User>(HttpStatusCode.OK, user);
                    else
                        return Request.CreateResponse(HttpStatusCode.NotFound);
                }
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                throw ExeptionUtils.ThrowCustomException(ex);
            }
        }

        [HttpDelete]
        public HttpResponseMessage DeleteUser(string id)
        {
            try
            {
                User user = this.userRepository.GetUserById(id);
                if (user != null)
                {
                    if (this.userRepository.Delete(user.Id))
                        return Request.CreateResponse(HttpStatusCode.OK);
                    else
                        return Request.CreateResponse(HttpStatusCode.NotAcceptable);
                }
                else
                    return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            catch (Exception ex)
            {
                throw ExeptionUtils.ThrowCustomException(ex);
            }
        }

        //[HttpGet]
        //[ActionName("GetAllMessageByUser")]
        //public HttpResponseMessage GetAllMessageByUser(string userId)
        //{
        //    if (string.IsNullOrEmpty(userId))
        //        return Request.CreateErrorResponse(HttpStatusCode.NoContent, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_USERNAME);
        //    try
        //    {
        //        User _user = this.userRepository.GetUserById(userId);
        //        if (_user == null)
        //            return Request.CreateResponse(HttpStatusCode.NotFound);
        //        if (_user.UserType == DBEntity.UserType.User)
        //            return Request.CreateErrorResponse(HttpStatusCode.NoContent, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.USER_UNVALID_PERMISSION);

        //        IEnumerable<Message> msg = this.userRepository.GetAllMessageByUser(userId);
        //        if (msg != null)
        //            return Request.CreateResponse<IEnumerable<Message>>(HttpStatusCode.OK, msg);
        //        else
        //            return Request.CreateResponse(HttpStatusCode.NotFound);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ExeptionUtils.ThrowCustomException(ex);
        //    }            
        //}

        [HttpPost]
        public HttpResponseMessage GetLocationFormDateToDate(AccountModel.WebServiceLocation mode)
        {
            
            //this.userRepository.GetAllLocationFormDateToDateForDeviceByUser(mode.deviceId,mode.formDate,mode.toDate,mode.userId);
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }

        [HttpPost]
        public HttpResponseMessage AddNewMessage([FromBody]  AccountModel.WebServiceAddNewMsg newMsg)
        {
            #region old_func
            //if (string.IsNullOrEmpty(newMsg.UserId))
            //    return Request.CreateErrorResponse(HttpStatusCode.NoContent, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.UNVALID_LOGIN_USER);
            //if (string.IsNullOrEmpty(newMsg.DeviceId))
            //    return Request.CreateErrorResponse(HttpStatusCode.NoContent, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.DEVICE_NOTREGISTED);
            //Models.EntytiRepossitory.WebServiceResult wsr = new Models.EntytiRepossitory.WebServiceResult();
            //try
            //{
            //    User user = this.userRepository.GetUserById(newMsg.UserId);
            //    if (user == null)
            //    {
            //        wsr.Status = HttpStatusCode.NotFound.ToString();
            //        wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.USER_NOTFOUND;
            //        return Request.CreateResponse<Models.EntytiRepossitory.WebServiceResult>(HttpStatusCode.NotFound, wsr);
            //    }

            //    Device dv = this.userRepository.GetDeviceById(newMsg.DeviceId, newMsg.UserId) ;
            //    if (dv == null)
            //    {
            //        wsr.Status = HttpStatusCode.NotFound.ToString();
            //        wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.DEVICE_NOTFOUND;
            //        return Request.CreateResponse<Models.EntytiRepossitory.WebServiceResult>(HttpStatusCode.NotFound, wsr);
            //    }
            //    Message msg = new Message();
            //    msg.Id = Guid.NewGuid().ToString();                                
                
            //    msg.NumberSendReceive = newMsg.NumberSendReceive;
            //    msg.SendDateTime = newMsg.DateTime;
            //    msg.UserMessage = newMsg.MessageText;
            //    msg.Type = (newMsg.Type == 1 ? DBEntity.SendReceiveType.Send : DBEntity.SendReceiveType.Receive);
            //    msg.MessageType = MessageType(newMsg.MessageType);
            //    msg.Status = DBEntity.ObjectStatus.Active;
            //    msg.LastModifined = DateTime.UtcNow;

            //    if ((this.ModelState.IsValid) && (msg != null))
            //    {
            //        Message _newMsg = this.userRepository.AddNewMassage(msg, newMsg.UserId);
            //        if (_newMsg != null)
            //        {
            //            wsr.Status = HttpStatusCode.Created.ToString();                        
            //            wsr.DeviceId = dv.Id;
            //            wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.ADD_NEW_MSG_SUCCESS;

            //            var httpRespone = Request.CreateResponse<Models.EntytiRepossitory.WebServiceResult>(HttpStatusCode.Created, wsr);
            //            string uri = Url.Link("DefaultApi", new { id = wsr.Id});
            //            httpRespone.Headers.Location = new Uri(uri);
            //            return httpRespone;
            //        }
            //        wsr.Status = HttpStatusCode.ExpectationFailed.ToString();
            //        wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.DEVICE_NOTFOUND;
            //        return Request.CreateResponse<Models.EntytiRepossitory.WebServiceResult>(HttpStatusCode.ExpectationFailed, wsr);
            //    }
            //    return Request.CreateResponse(HttpStatusCode.BadRequest);
            //}
            //catch (Exception ex)
            //{
            //    throw ExeptionUtils.ThrowCustomException(ex);
            //}  
            #endregion 

            if (string.IsNullOrEmpty(newMsg.DeviceId))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_DEVICE);
            if (string.IsNullOrEmpty(newMsg.MessageText.ToString()))
                return null;          

            AccountModel.WebServiceResult wsr = new AccountModel.WebServiceResult();
            try
            {
                //Checking if message exists
                string _uuid = "";
                if (newMsg.MessageType == 0)
                    _uuid =  ConvertUtils.CreateUuidForSMS( newMsg.DateTime, newMsg.NumberSendReceive, newMsg.Type.ToString());                
                else
                    _uuid = newMsg.Uuid;
                if (this.userRepository.CheckingMessageExists(newMsg.DeviceId, newMsg.UserId,_uuid))
                {
                    wsr.Status = HttpStatusCode.BadRequest.ToString();
                    wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.MESSAGE_IS_EXISTS;
                    return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
                }
                Message msg = new Message();
                msg.Id = Guid.NewGuid().ToString();
                //Add uuid for sms
                if (msg.MessageType == 0)
                {
                    msg.Uuid = _uuid;
                    wsr.Uuid = _uuid;
                }
                msg.NumberSendReceive = newMsg.NumberSendReceive;
                msg.SendDateTime = newMsg.DateTime;
                msg.UserMessage = newMsg.MessageText;
                msg.Type = (newMsg.Type == 0 ? DBEntity.SendReceiveType.Send : DBEntity.SendReceiveType.Receive);
                msg.MessageType = MessageType(newMsg.MessageType);
                msg.Status = DBEntity.ObjectStatus.Active;
                msg.LastModifined = DateTime.UtcNow;

                if ((this.ModelState.IsValid) && (msg != null))
                {
                    try
                    {                        
                        User _user = this.userRepository.GetUserById(newMsg.UserId);
                        if(userRepository == null )
                            return Request.CreateResponse(HttpStatusCode.BadRequest);
                        Device _device = this.userRepository.GetDeviceByUserName(newMsg.DeviceId, _user.UserName);
                        if (_device != null)
                        {
                            //this.userRepository.CheckExpireDevice(_device.Id, _user.Id);
                            if (_device.Messages == null)
                                _device.Messages = new List<Message>();
                            _device.Messages.Add(msg);
                            wsr.Status = HttpStatusCode.Created.ToString();
                            wsr.Id = _device.Id;

                            if (this.userRepository.UpdateDeviceByDeviceId(_device.Id, _device, _user.UserName))
                                wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.ADD_NEW_MSG_SUCCESS;
                            else
                                wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.DEVICE_NOTFOUND;
                            var httpRespone = Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.Created, wsr);
                            string uri = Url.Link("DefaultApi", new { id = wsr.Id });
                            httpRespone.Headers.Location = new Uri(uri);
                            return httpRespone;
                        }
                        return Request.CreateResponse(HttpStatusCode.BadRequest);
                    }
                    catch (Exception ex)
                    {
                        wsr.Status = HttpStatusCode.BadRequest.ToString();
                        wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.DUPLICATE_USERNAME;
                        return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
                    }
                }
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                throw ExeptionUtils.ThrowCustomException(ex);
            }
        }

        public DBEntity.MessageType MessageType(int i)
        {
            switch (i)
            {
                case 0:
                    return DBEntity.MessageType.SMS;
                case 1:
                    return DBEntity.MessageType.VIBER;
                default:
                    return DBEntity.MessageType.SMS;
            }
        }
            
        private string UpdateAndAddNewDevice(string userId, string imei, string sn, string deviceName, string osVersion, string osBrand, string screenSize, string appVersion, string appInstalledOn)
        {
            try
            {
                if (string.IsNullOrEmpty(imei))
                    imei = "";
                if (string.IsNullOrEmpty(deviceName))
                    deviceName = "Untitled Name";
                if (string.IsNullOrEmpty(osVersion))
                    osVersion = "";
                if (string.IsNullOrEmpty(osBrand))
                    osBrand = "";
                if (string.IsNullOrEmpty(screenSize))
                    screenSize = "";
                if (string.IsNullOrEmpty(appVersion))
                    appVersion = "";
                if (string.IsNullOrEmpty(appInstalledOn))
                    appInstalledOn = "";
                if (string.IsNullOrEmpty(sn))
                    sn = "";

                Device dv = this.userRepository.GetDeviceBySerialNumber(sn,userId);
                if (dv != null)
                {                   
                    if (string.IsNullOrEmpty(dv.Imei1))
                        dv.Imei1 = imei;
                    else
                        if (string.IsNullOrEmpty(dv.Imei2))
                            dv.Imei2 = imei;
                    dv.LastModifined = DateTime.UtcNow;
                    dv.DeviceName = deviceName;
                    dv.OsVersion = osVersion;
                    dv.OsBrand = osBrand;
                    dv.ScreenSize = screenSize;
                    dv.AppVersion = appVersion;
                    dv.AppInstalledOn = appInstalledOn;
                    if (this.userRepository.UpdateDeviceBySerial(sn,dv, userId))
                        return dv.Id.ToString();
                    else
                        return "4";
                }
                else
                {
                    Device newDevice = new Device();
                    newDevice.Id = Guid.NewGuid().ToString();                    
                    newDevice.Imei1 = imei;                    
                    newDevice.Sn = sn;                    
                    newDevice.DeviceName = deviceName;
                    //newDevice.ExpireDate = DateTime.Parse(appInstalledOn.ToString()).AddDays(7);
                    newDevice.OsVersion = osVersion;
                    newDevice.OsBrand = osBrand;
                    newDevice.ScreenSize = screenSize;
                    newDevice.AppVersion = appVersion;
                    newDevice.AppInstalledOn = appInstalledOn;
                    newDevice.Status = DBEntity.ObjectStatus.Active;
                    newDevice.LastModifined = DateTime.UtcNow;
                    //newDevice.ExpireDate = DateTime.ParseExact(appInstalledOn, "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture).AddDays(7);
                    newDevice.ExpireDate = DateTime.ParseExact(appInstalledOn, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture).AddDays(7);
                    if ((this.ModelState.IsValid) && (newDevice != null))
                    {
                        Device newDv = this.userRepository.AddNewDevice(newDevice, userId);
                        if (newDv != null)
                        {                      
                            return newDv.Id.ToString();
                        }
                        return "3";
                    }
                    return "0";
                }
            }
            catch (Exception ex)
            {
                throw ExeptionUtils.ThrowCustomException(ex);
            }  
        }

        [HttpPost]
        public HttpResponseMessage RegistrationID(AccountModel.RegisNotifitration model)
        {
            if (string.IsNullOrEmpty(model.deviceId))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_DEVICE);
            if (string.IsNullOrEmpty(model.userName.ToString()) || string.IsNullOrEmpty(model.userName.ToString()))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_USERNAME);
            if(string.IsNullOrEmpty(model.registrationId.ToString()))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_REGISTRATION_ID);
            
            AccountModel.WebServiceResult wsr = new AccountModel.WebServiceResult();
            try
            {
                if(this.userRepository.RegistrationID(model.deviceId, model.userName, model.registrationId))
                {
                    wsr.Status = HttpStatusCode.Created.ToString();
                    wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.ADD_NEW_REGISTRATION_ID_SUCCESS;
                }
                else                  
                {
                        wsr.Status = HttpStatusCode.BadRequest.ToString();
                        wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.ADD_NEW_REGISTRATION_ID_ERROR;
                        return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
                }
                return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
            }
            catch (Exception ex)
            {
                throw ExeptionUtils.ThrowCustomException(ex);
            }
        }

        public HttpResponseMessage UnRegistrationID(AccountModel.RegisNotifitration model)
        {
            if (string.IsNullOrEmpty(model.deviceId))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_DEVICE);
            if (string.IsNullOrEmpty(model.userName.ToString()) || string.IsNullOrEmpty(model.userName.ToString()))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_USERNAME);
            if (string.IsNullOrEmpty(model.registrationId.ToString()))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_REGISTRATION_ID);

            AccountModel.WebServiceResult wsr = new AccountModel.WebServiceResult();
            try
            {
                if (this.userRepository.UnRegistrationID(model.deviceId, model.userName, model.registrationId))
                {
                    wsr.Status = HttpStatusCode.Created.ToString();
                    wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.UNREGISTRATION_ID_SUCCESS;
                }
                else
                {
                    wsr.Status = HttpStatusCode.BadRequest.ToString();
                    wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.UNREGISTRATION_ID_ERROR;
                    return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
                }
                return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
            }
            catch (Exception ex)
            {
                throw ExeptionUtils.ThrowCustomException(ex);
            }
        }

        [HttpPost]
        public HttpResponseMessage PushNotification(AccountModel.PushNotifitration model)
        {
            if (string.IsNullOrEmpty(model.deviceId))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_DEVICE);
            if (string.IsNullOrEmpty(model.userName.ToString()) || string.IsNullOrEmpty(model.userName.ToString()))
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.EMPTY_USERNAME);            

            AccountModel.WebServiceResult wsr = new AccountModel.WebServiceResult();
            try
            {
                if(this.userRepository.PushNotification(model.deviceId, model.userName, model.Message) != null)
                {
                    wsr.Status = HttpStatusCode.Created.ToString();
                    wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.PUSH_NOTIFITRATION_SUCCESSFUL;
                }
                else                  
                {
                        wsr.Status = HttpStatusCode.BadRequest.ToString();
                        wsr.Message = SpyApp.Models.BaseCommon.MSG_STR.AUTH_MESSAGE_STRING.PUSH_NOTIFITRATION_ERROR;
                        return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
                }
                return Request.CreateResponse<AccountModel.WebServiceResult>(HttpStatusCode.BadRequest, wsr);
            }
            catch (Exception ex)
            {
                throw ExeptionUtils.ThrowCustomException(ex);
            }        
        }
    }
}
